package com.warrior.gatherserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.warrior.gathercommon.common.ResultCode;
import com.warrior.gathercommon.constants.CommonStatus;
import com.warrior.gathercommon.dto.GatherProDto;
import com.warrior.gatherserver.grpc.GpcResponse;
import com.warrior.gatherserver.grpc.Messages;
import com.warrior.gatherserver.grpc.MessageServiceGrpc;
import com.warrior.gatherserver.service.MessageService;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @ClassName com.warrior.gatherservice.service.impl.GrpcServerService.java
 * @Author xujian
 * @Description
 * @CreateTime 2020年12月21日 16:18:00
 */
@GrpcService
public class GrpcServerService extends MessageServiceGrpc.MessageServiceImplBase {

    @Autowired
    private MessageService messageService;

    @Override
    public void sendMessages(Messages request,
                             StreamObserver<GpcResponse> responseObserver) {
        int type = request.getType();
        String result = null;
        GpcResponse response = null;
        //接受客户端采集数据
        if (CommonStatus.CONSTANT_GRPC_SERVICE_SEND_MESSAGE == type) {
            result = messageService.handleMessage(request);
            if (StringUtils.isEmpty(result)) {
                response = GpcResponse.newBuilder().setStatus(ResultCode.SUCCEED_CODE).build();
            } else {
                response = GpcResponse.newBuilder().setStatus(ResultCode.FAIL_CODE).setMessage(result).build();
            }
        }
        //给客户端发送配置数据
        if(CommonStatus.CONSTANT_GRPC_SERVICE_RECEVE_CONFIG == type){
            List<GatherProDto> properties = messageService.getProperties();
            response = GpcResponse.newBuilder().setStatus(ResultCode.SUCCEED_CODE).setData(JSONObject.toJSONString(properties)).build();
        }

        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

}
